Write a function that returns the number of vowels used in a string. Vowels are the characters 'a', 'e', 'i', 'o', and 'u'.
vowels('Hi There!') --> 3
vowels('Why do you ask?') --> 4
vowels('Why?') --> 0
Two solutions:
1. Iteractive
Array.prototype.includes()
2. Regular expression
String.prototype.match()
function vowels(str) {
// avoid same name with function, use array/ string?
let vowel = ['a', 'e', 'i', 'o', 'u'];
let counter = 0;
for (let char of str.toLowerCase()){
if (vowel.includes(char)){
counter++;
}
}
return counter;
}
function vowels(str) {
// g: do not stop at the first match, i: case insensitive
const matches = str.match(/[aeiou]/gi)
return matches ? matches.length : 0;
}
vowels('Hi There!')
vowels('Why do you ask?')
vowels('Why?')